import React, { useEffect, useState } from 'react';
import { FieldsGrid, TitleGrid } from './stores/definitions';
import { t } from '@lingui/macro';
import { Form } from '@alifd/next';
import { observable, toJS } from 'mobx';
import { observer } from 'mobx-react-lite';
import CompanySelect from './CompanySelect';
import SurchargesTable from './SurchargesTable';
import { useStore } from '@/hooks';
import CarrierPriceInput from './CarrierPriceInput';
import MerchantSurchargesTable from './MerchantSurchargesTable';
import OrderSurchargeList from './OrderSurchargeList';

const CarrierInfo = (props) => {
  const {
    form,
    order,
    task,
    key,
    type,
    index,
    calculate,
    isPreview,
    step,
  } = props;
  const { orderChangeStore: store } = useStore();
  const [taskFormData] = useState(() => observable({}));
  const [tableDataSource, setTableDataSource] = useState({});
  const [defaultKeys, setDefaultKeys] = useState([]);
  const [curSurcharges, setCurSurcharge] = useState({});
  const merchant = order?.merchant;
  useEffect(() => {
    if (step === index + 1) {
      _.assign(taskFormData, {
        ...task,
        ORDER: order,
        FORM: form.formData,
      });
    }
  }, [step]);

  useEffect(() => {
    (async () => {
      await store.updateBaseRoadPrice(toJS(form.formData));

      const curTaskInfo = toJS(form.formData)?.taskInfo[index];
      const { dataSource = [] } = toJS(store.options.company).find((e) => e.type === type) || {};
      const curCompanyIds = dataSource.reduce((res, cur) => {
        const { value: companyId } = cur;
        res.push(companyId);
        return res;
      }, []);
      const companyId = curCompanyIds.includes(curTaskInfo?.companyId) ? curTaskInfo?.companyId : task?.companyId;
      const surcharges = dataSource.find((e) => e.value === companyId)?.surcharge || {};

      const tableData = await store.formatSurchargeTableInfo(surcharges, task?.selectedSurchargeKeys, order?.merchant);
      setTableDataSource(tableData);
      setCurSurcharge(() => ([surcharges]));
    })();
  }, []);

  useEffect(() => {
    (async () => {
      const carrierPrice = await store.updateCompanyPrice(toJS(form.formData), task, index);
      if (!taskFormData?.carrierPrice) {
        _.assign(taskFormData, { carrierPrice });
      }
      _.assign(taskFormData, { suggestCarrierPrice: carrierPrice });
      setDefaultKeys(() => (taskFormData?.selectedSurchargeKeys));

      const { TASK } = toJS(form.formData);
      const sourceCompanyIdMap = {
        direct: TASK?.carrierCompany,
        from: TASK?.fromTask?.carrierCompany,
        to: TASK?.toTask?.carrierCompany,
      };
      const { carrierPrice: curCarrierPrice, companyId, companyName } = toJS(taskFormData);
      calculate.setParam('direction', index === 1);
      calculate.setParam('sourceCompanyId', sourceCompanyIdMap[type]);
      calculate.setParam('companyPrice', curCarrierPrice);
      calculate.setParam('newCompanyId', companyId);
      calculate.setParam('newCompanyName', companyName);
    })();
  }, [type]);

  useEffect(() => {
    if (!_.isEmpty(curSurcharges)) {
      const surcharges = _.cloneDeep(curSurcharges[index]);
      _.assign(taskFormData, {
        surcharges,
      });
      const newTaskInfo = _.cloneDeep(form?.formData?.taskInfo) || [];
      newTaskInfo[index] = toJS(taskFormData);
      _.assign(form.formData, { taskInfo: newTaskInfo });
    }
  }, [curSurcharges]);


  const handleChange = async (values, item) => {
    const { name, value } = item;
    let fieldValue = value;
    if (name === 'company') {
      const { surcharges: newCompanySur, ...newFormData } = fieldValue;
      setDefaultKeys(() => (toJS(taskFormData?.selectedSurchargeKeys)));
      // 处理公司字段
      _.assign(taskFormData, {
        ...newFormData,
      });
      const surcharges = await store.formatNewSurchargeTableInfo(newCompanySur, toJS(taskFormData.selectedSurchargeKeys), toJS(taskFormData), type);
      _.assign(taskFormData, {
        surcharges: surcharges[index],
      });

      const carrierPrice = await store.updateCompanyPrice(toJS(form.formData), toJS(taskFormData), index);
      if (!taskFormData?.carrierPrice) {
        _.assign(taskFormData, { carrierPrice });
      }
      _.assign(taskFormData, {
        suggestCarrierPrice: carrierPrice,
      });
      const { carrierPrice: curCarrierPrice } = toJS(taskFormData);
      calculate.setParam('companyPrice', curCarrierPrice);
    } else if (name === 'selectedSurKeys') {
      // 处理渠道附加费字段
      const selectedKeyParams = [...value, ...taskFormData.selectedMerchantSurKeys];
      const surcharges = await store.formatNewSurchargeTableInfo(values.surcharges, selectedKeyParams, values, type);

      _.assign(taskFormData, {
        selectedSurKeys: fieldValue,
        selectedSurchargeKeys: selectedKeyParams,
        surcharges: surcharges[index],
      });
      const carrierPrice = await store.updateCompanyPrice(toJS(form.formData), toJS(taskFormData), index);
      if (!taskFormData?.carrierPrice) {
        _.assign(taskFormData, { carrierPrice });
      }
      _.assign(taskFormData, {
        suggestCarrierPrice: carrierPrice,
      });

      const { carrierPrice: curCarrierPrice } = toJS(taskFormData);
      setDefaultKeys(() => (selectedKeyParams));
      setCurSurcharge(() => (surcharges));
      calculate.setParam('companyPrice', curCarrierPrice);
    } else if (name === 'selectedMerchantSurKeys') {
      // 处理商户附加费字段
      const selectedKeyParams = [...value, ...taskFormData.selectedSurKeys];
      const surcharges = await store.formatNewSurchargeTableInfo(values.surcharges, selectedKeyParams, values, type);
      _.assign(taskFormData, {
        selectedMerchantSurKeys: fieldValue,
        selectedSurchargeKeys: selectedKeyParams,
        surcharges: surcharges[index],
      });
      setDefaultKeys(() => (selectedKeyParams));
      setCurSurcharge(() => (surcharges));
    } else if (name === 'carrierPrice') {
      // 处理公司费用字段
      _.set(taskFormData, name, fieldValue);
      const { companyId, companyName } = toJS(taskFormData);
      calculate.setParam('companyPrice', Number(fieldValue));
      calculate.setParam('newCompanyId', companyId);
      calculate.setParam('newCompanyName', companyName);
    } else if (name === 'driver') {
      _.assign(taskFormData, {
        ...fieldValue,
      });
    } else if (name === 'dispatchOrderRemarks') {
      store.dispatchOrderRemarks = value;
    } else {
      // 处理其他字段
      _.set(taskFormData, name, fieldValue);
    }

    saveInFormData();
  };

  const handleChangeTableDataSource = async (surcharge) => {
    const tableData = await store.formatSurchargeTableInfo(surcharge, toJS(defaultKeys), order?.merchant);
    setTableDataSource((pre) => ({ ...tableData }));
  };

  function saveInFormData() {
    if (type === 'direct') {
      _.assign(form.formData, { taskInfo: [toJS(taskFormData)] });
    } else {
      const newTaskInfo = form.formData.taskInfo || [];
      newTaskInfo[index] = toJS(taskFormData) || {};
      _.assign(form.formData, { taskInfo: newTaskInfo });
    }
  }

  return (
    <>
      <Form
        inline
        isPreview={isPreview}
        value={toJS(taskFormData)}
        onChange={handleChange}
      >
        <OrderSurchargeList
          key="sur"
          order={order}
          index={index}
          form={form}
          type="sur"
        />
        <TitleGrid title={t`承运信息`} />
        <CompanySelect
          record={toJS(taskFormData)}
          name={'companyId'}
          value={taskFormData.companyId}
          type={type}
          handleChange={handleChange}
          handleChangeTableDataSource={handleChangeTableDataSource}
          calculate={calculate}
          mode={isPreview ? 'view' : 'edit'}
        />
        <SurchargesTable
          dataSource={toJS(tableDataSource)}
          taskFormData={toJS(taskFormData)}
          handleChange={handleChange}
          mode={isPreview ? 'view' : 'edit'}
        />
        {merchant &&
          <>
            <OrderSurchargeList
              key="merchant"
              form={form}
              order={order}
              index={index}
              type="merchant"
            />
            <MerchantSurchargesTable
              merchant={merchant}
              surchargesData={toJS(tableDataSource)}
              taskFormData={toJS(taskFormData)}
              handleChange={handleChange}
              mode={isPreview ? 'view' : 'edit'}
            />
          </>
        }
        <TitleGrid title={t`派车信息`} />
        <FieldsGrid
          formData={toJS(taskFormData)}
          mode={isPreview ? 'view' : 'edit'}
          fields={['driver', 'licenseNo.mainland', 'licenseNo.hk']}
        />
        <CarrierPriceInput
          formData={toJS(taskFormData)}
          onChange={handleChange}
          calculate={calculate}
        />
        <FieldsGrid
          formData={toJS(taskFormData)}
          onChange={handleChange}
          mode={isPreview ? 'view' : 'edit'}
          fields={['dispatchOrderRemarks']}
        />
      </Form>
    </>
  );
};

export default observer(CarrierInfo);
